import { ApiMethodDecorator } from './decorator';
import { defHttp } from '/@/utils/http/axios';
import { isArray } from '/@/utils/is';

export type MethodType = 'get'|'post'|'put'|'delete'

export class BasicApi<C = any, U = any, L = any, R = any> {
  path!: string;
  constructor(protected axios = defHttp) {}

  request<T>(
    method: MethodType,
    argument: { data?: T; url?: Array<number | string> | string | number },
  ) {
    const url =
      this.path +
      (argument.url
        ? isArray(argument.url)
          ? `/${argument.url.join('/')}`
          : `/${argument.url}`
        : '');
    const params = { url };
    if (argument.data) params['data'] = argument.data;
    return this.axios[method](params);
  }

  @ApiMethodDecorator('post')
  create(data?: C) {
    return this.request<C>('post', { data });
  }

  @ApiMethodDecorator('put')
  update(data?: U) {
    return this.request<U>('put', { data });
  }

  @ApiMethodDecorator('delete', ':id')
  delete(id: string) {
    return this.request<any>('delete', { url: [id] });
  }

  @ApiMethodDecorator('post', 'list')
  list(data?: R): Promise<L> {
    return this.request<R>('post', { data, url: ['list'] });
  }
}
